package com.easyOrder.core.duplicate;

import com.easyOrder.core.cache.CacheKeyPrefix;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Token生成器
 */
public class DuplicateSubmissionTokenProcessor {
	
	private static class SingleTonHolder {
		private static DuplicateSubmissionTokenProcessor instance = new DuplicateSubmissionTokenProcessor();
	}

	public static DuplicateSubmissionTokenProcessor getInstance() {
		return SingleTonHolder.instance;
	}

	protected DuplicateSubmissionTokenProcessor() {
		super();
	}
	
	public static String getCacheKey(String sessionId, BusinessType businessTypes) {
		return CacheKeyPrefix.DuplicateSubmission.getKey() + sessionId + "_" + businessTypes.getValue();
	}

	public String generateToken(HttpServletRequest request) {

		HttpSession session = request.getSession();
		try {
			byte id[] = session.getId().getBytes();
			byte now[] = new Long(System.currentTimeMillis()).toString().getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(id);
			md.update(now);
			return this.toHex(md.digest());

		} catch (IllegalStateException e) {
			return null;
		} catch (NoSuchAlgorithmException e) {
			return null;
		}

	}

	public String toHex(byte buffer[]) {
		StringBuffer sb = new StringBuffer();
		String s = null;
		for (int i = 0; i < buffer.length; i++) {
			s = Integer.toHexString((int) buffer[i] & 0xff);
			if (s.length() < 2) {
				sb.append('0');
			}
			sb.append(s);
		}
		return sb.toString();
	}

	public String generateToken(HttpServletRequest request,
			BusinessType businessTypes) {
		HttpSession session = request.getSession();
		try {
			byte id[] = session.getId().getBytes();
			byte now[] = new Long(System.currentTimeMillis()).toString().getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(id);
			md.update(businessTypes.getValue().toString().getBytes());
			md.update(now);
			return this.toHex(md.digest());

		} catch (IllegalStateException e) {
			return null;
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

}
